// 引入 Element Plus 样式
import 'element-plus/dist/index.css';

import { createApp } from 'vue';
import type { App as VueApp } from 'vue';
import { createPinia } from 'pinia';
import ElementPlus from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import { renderWithQiankun, type QiankunProps } from 'vite-plugin-qiankun/dist/helper';
import Cookies from 'js-cookie';

import App from './App.vue';
import router from './router';
import { addDateRange, handleTree, parseTime, resetForm, selectDictLabel, selectDictLabels } from './utils/ruoyi';
import { download } from './utils/request';
import { $modal } from './utils/modal';
import { getToken } from './utils/auth';

// 声明qiankun全局变量
declare global {
  interface Window {
    __POWERED_BY_QIANKUN__?: boolean;
  }
}

// 常量定义
const APP_NAME = 'ToolApp';
const ROUTE_BASE = '/tool';
const CONTAINER_SELECTORS = ['#micro-container', '#tool-app-app', '#tool-app'];

// 应用实例
let app: VueApp<Element> | null = null;

/**
 * 配置全局属性
 */
function setupGlobalProperties(app: VueApp, props: QiankunProps) {
  // 注册工具函数
  const globalProperties = app.config.globalProperties;
  globalProperties.parseTime = parseTime;
  globalProperties.resetForm = resetForm;
  globalProperties.addDateRange = addDateRange;
  globalProperties.selectDictLabel = selectDictLabel;
  globalProperties.selectDictLabels = selectDictLabels;
  globalProperties.download = download;
  globalProperties.handleTree = handleTree;
  globalProperties.$modal = $modal;
  globalProperties.$cookies = Cookies;
  globalProperties.getToken = getToken;

  // 注入微前端通信接口
  if (props?.getGlobalState) {
    globalProperties.$getGlobalState = props.getGlobalState;
  }
  if (props?.setGlobalState) {
    globalProperties.$setGlobalState = props.setGlobalState;
  }
  if (props?.messageService) {
    globalProperties.$messageService = props.messageService;
  }
}

/**
 * 查找挂载容器
 */
function findContainer(props: QiankunProps): HTMLElement {
  // 1. 优先使用 props 中的容器
  if (props?.container) {
    if (typeof props.container === 'string') {
      const element = document.querySelector<HTMLElement>(props.container);
      if (element) {
        console.log(`[${APP_NAME}] 使用props指定容器: "${props.container}"`);
        return element;
      }
    } else {
      const container = props.container as any;
      if (container && container instanceof HTMLElement) {
        console.log(`[${APP_NAME}] 使用props提供的DOM元素`);
        return container;
      }
    }
  }

  // 2. 尝试默认容器选择器
  for (const selector of CONTAINER_SELECTORS) {
    const element = document.querySelector<HTMLElement>(selector);
    if (element) {
      console.log(`[${APP_NAME}] 使用默认容器: "${selector}"`);
      return element;
    }
  }

  // 3. 最后使用 body
  console.warn(`[${APP_NAME}] 未找到指定容器，使用 document.body`);
  return document.body;
}

// 路由同步标记，避免重复设置
let routeSyncSetup = false;

/**
 * 设置路由同步（微前端模式下监听主应用路由变化）
 */
function setupRouteSync(_props: QiankunProps) {
  // 避免重复设置
  if (routeSyncSetup) {
    console.log(`[${APP_NAME}] 路由同步已设置，跳过`);
    return;
  }
  
  console.log(`[${APP_NAME}] 设置路由同步监听`);
  
  // 监听浏览器路由变化
  const handleRouteChange = () => {
    const currentPath = window.location.pathname;
    console.log(`[${APP_NAME}] 检测到路由变化:`, currentPath);
    
    // 如果是 tool-app 的路径，直接使用完整路径
    if (currentPath.startsWith(ROUTE_BASE)) {
      console.log(`[${APP_NAME}] 完整路径:`, currentPath, '当前路由:', router?.currentRoute.value.path);
      
      // 如果完整路径与当前路由不同，则跳转
      if (router && router.currentRoute.value.path !== currentPath) {
        console.log(`[${APP_NAME}] 跳转到:`, currentPath);
        router.push(currentPath).catch(err => {
          console.warn(`[${APP_NAME}] 路由跳转失败:`, err);
        });
      }
    }
  };
  
  // 监听 popstate 事件
  window.addEventListener('popstate', handleRouteChange);
  
  // 监听 pushState 和 replaceState（只在未设置时修改）
  if (!(window as any).__TOOL_APP_ROUTE_SYNC__) {
    const originalPushState = history.pushState;
    const originalReplaceState = history.replaceState;
    
    history.pushState = function(...args) {
      originalPushState.apply(history, args);
      handleRouteChange();
    };
    
    history.replaceState = function(...args) {
      originalReplaceState.apply(history, args);
      handleRouteChange();
    };
    
    (window as any).__TOOL_APP_ROUTE_SYNC__ = true;
  }
  
  // 初始化时立即检查一次
  handleRouteChange();
  
  // 再延迟检查一次，确保路由已更新
  setTimeout(handleRouteChange, 50);
  
  routeSyncSetup = true;
  console.log(`[${APP_NAME}] ✅ 路由同步监听设置完成`);
}

/**
 * 创建应用实例
 */
function createMicroApp(props: QiankunProps = {}) {
  console.log(`[${APP_NAME}] 创建应用，props:`, props);

  // 创建 Vue 应用实例
  app = createApp(App);

  // 配置 Pinia
  const pinia = createPinia();
  app.use(pinia);

  // 配置路由
  app.use(router);

  // 配置 Element Plus（提高全局 zIndex 防止弹框被遮罩盖住）
  app.use(ElementPlus, { locale: zhCn, zIndex: 4000 });

  // 注册 Element Plus 图标
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
  }

  // 配置全局属性
  setupGlobalProperties(app, props);

  // 查找挂载容器
  const container = findContainer(props);

  // 为微前端环境添加标识类
  const isMicroFrontend = props?.container || window.__POWERED_BY_QIANKUN__;
  console.log(`[${APP_NAME}] 环境检测:`, {
    'props.container': !!props?.container,
    '__POWERED_BY_QIANKUN__': !!window.__POWERED_BY_QIANKUN__,
    'isMicroFrontend': isMicroFrontend
  });
  
  if (isMicroFrontend) {
    container.classList.add('micro-frontend');
    console.log(`[${APP_NAME}] 微前端环境，添加样式标识`);
  }

  // 挂载应用
  try {
    app.mount(container);
    console.log(`[${APP_NAME}] ✅ 应用挂载成功`);
    
    // 在微前端环境下，监听主应用路由变化
    if (isMicroFrontend) {
      console.log(`[${APP_NAME}] 微前端环境，设置路由同步`);
      setupRouteSync(props);
    } else {
      console.log(`[${APP_NAME}] 独立模式，不设置路由同步`);
    }
  } catch (error) {
    console.error(`[${APP_NAME}] ❌ 应用挂载失败:`, error);
    throw error;
  }

  // 返回应用实例和卸载函数
  return {
    app,
    unmount: async () => {
      console.log(`[${APP_NAME}] 卸载应用`);
      if (app) {
        try {
          await new Promise((resolve) => setTimeout(resolve, 0));
          app.unmount();
          console.log(`[${APP_NAME}] ✅ 应用卸载成功`);
        } catch (error) {
          console.warn(`[${APP_NAME}] ⚠️ 卸载时出现错误:`, error);
        } finally {
          app = null;
        }
      }
    },
  };
}

/**
 * 智能检测运行环境
 */
function detectRunningMode(): boolean {
  // 只通过 qiankun 标志判断是否为微前端模式
  const hasQiankunFlag = !!window.__POWERED_BY_QIANKUN__;

  console.log(`[${APP_NAME}] 环境检测:`, {
    hasQiankunFlag,
    pathname: window.location.pathname,
    result: hasQiankunFlag ? '微前端模式' : '独立模式',
  });

  return hasQiankunFlag;
}

/**
 * Qiankun 生命周期配置
 */
renderWithQiankun({
  bootstrap() {
    console.log(`[${APP_NAME}] qiankun bootstrap - 应用初始化`);
  },

  mount(props) {
    console.log(`[${APP_NAME}] qiankun mount - 应用挂载`, props);
    
    // 设置微前端环境标志
    (window as any).__POWERED_BY_QIANKUN__ = true;
    console.log(`[${APP_NAME}] 设置微前端环境标志: __POWERED_BY_QIANKUN__ = true`);
    
    createMicroApp({
      ...props,
      routerBase: ROUTE_BASE,
    });
  },

  unmount() {
    console.log(`[${APP_NAME}] qiankun unmount - 应用卸载`);
    
    // 清除微前端环境标志
    (window as any).__POWERED_BY_QIANKUN__ = false;
    console.log(`[${APP_NAME}] 清除微前端环境标志: __POWERED_BY_QIANKUN__ = false`);
    
    if (app) {
      setTimeout(() => {
        try {
          app?.unmount();
          console.log(`[${APP_NAME}] ✅ qiankun 应用卸载成功`);
        } catch (error) {
          console.warn(`[${APP_NAME}] ⚠️ qiankun 卸载失败:`, error);
        } finally {
          app = null;
        }
      }, 0);
    }
  },

  update() {
    console.log(`[${APP_NAME}] qiankun update - 应用更新`);
  },
});

/**
 * 创建 Mock 服务（独立模式）
 */
function createMockServices() {
  return {
    getGlobalState: () => ({}),
    setGlobalState: () => {},
    messageService: {
      broadcast: () => {},
      subscribe: () => {},
      unsubscribe: () => {},
    },
  };
}

// ==================== 应用启动 ====================

const isMicroFrontend = detectRunningMode();

if (!isMicroFrontend) {
  // 独立模式启动
  console.log(`[${APP_NAME}] 🚀 以独立模式启动`);
  createMicroApp({
    routerBase: '/',
    container: '#tool-app-app' as any,
    ...createMockServices(),
  });
} else {
  // 微前端模式等待 qiankun 调用
  console.log(`[${APP_NAME}] ⏳ 微前端模式 - 等待 qiankun 调用 mount()`);
}

